var frameId = "";//获取获取当前layui frame的id
var sessionId = callVo != null ? callVo.sessionId : "";//通话id
var lastMsg = "";//上一次执行操作的信息
var formType = callVo != null ? callVo.formType : "";//外呼来源
var currentMsgType, desc;//当前状态信息 、描述
var isCallEnd = false;//是否结束通话操作 --- 用于控制状态返回的问题，当判断通话为结束的状态-->则不再接收此次通话的后续信息
var manualToCall = false;//手动执行下一条呼叫
var isAutoCall = true;//是否自动联动call
var hadReceiveCommitSuccess = false;//是否接收到提交成功标识
var isCancelCall = false;//是否取消外呼操作
var isCallException = false;//外呼异常
var isRedial = false;//是否执行重拨操作
var isStartTimeTask = false, startTimeTask; //双方通话计时标识/任务
var interruptCallUrl = "http://"+cloudcallUrl + "/callCenter/interruptCall";
var isDoNextCall = false;//是否执行下同call客操作
var selCustomerFollowVal = null;//选的反馈值
var connWsId = null;//当前websocket连接的Id
var timeOutToCallTarget = null;//超时外呼操作
var waitForCall = false;//监测后在发起外呼操作标识
var targetAnswer = false;//有双方接通？
var isSaveFeedBack = false;//是否以保存了反馈
var isCloseWin = false;//是否关闭窗体
var tipWinIndex = null;
var reCallTask = null;//用于定时监测 websocket连接是否正常 正常则返回提示
//---用于计时操作------
var min = 0, hour = 0, second = 0;
var robotAnswerId = 0;//显示AI返回的话术对话框的id标识
var isChangePc = false; //切换PC标识
var interruptCheckStatus = false; //停止状态监测
var receiveCallMessage = false;//接收外呼信息标识

var regTxt =/^([0-9]{3,4}-)?[0-9]{7,8}$/ ;
var regTelPhoneTxt =/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;

var thisUA = null;//此页面专用的SIPUA
var checkUaRegisterStatusCount = 3;//检测ua 注册情况的次数
var uaName = null;//登录 账号
var mainPhone,targetPhone;
var reConnectToCallCount = 3;//定义重新连接进行外呼操作次数 3
/**
 * 封装aiCall客的事件 ===》 避免localStroage的存储数据量过多
 * 类型： type
 *   值： value
 * 描述： desc
 * 时间戳 timeStamp ===> 时间戳 由于值的内容相同 localstorage 监听 是值改变了才会触发的
 * */
var AICallEvent = {
    createEvent: function (type, value, desc) {
        var aICallEvent = {};
        aICallEvent.type = type;
        aICallEvent.value = value;
        aICallEvent.desc = desc;
        return aICallEvent;
    }
};

//发送外呼任务
function call() {
    console.log("将信打包给信鸽，并让它进行送信操作");
    try {
        if (callVo != null) {
            //封装外呼参数
            mainPhone = callVo.mainCallPhone.replace("-","");
            targetPhone = setTargetCallPhone.replace("-","");
            if(commitTo == 8 ){
                mainPhone = uaName;
                targetPhone = callVo.mainCallPhone.replace("-","");
            }

            var callParameter = CallParameter.buildParam(mainPhone, targetPhone,
                callVo.whereFrom, callVo.pageFrom, callVo.machineFrom, callVo.mainCallType, commitTo,
                callVo.createUserId, callVo.customerName, callVo.token, callVo.cityId, isRedial,
                callVo.sessionId, callVo.callTaskId, connWsId, callTask.packageId,callVo.dataId);

            console.log(JSON.stringify(callParameter));
            // 通过广播的方式通知进行外呼操作 ===>connWsId 作为发送时指定对应websocket ,持有connWsId 的 websocket 才能进行处理 发送外呼操作
            localStorage.setItem("AICallEvent", JSON.stringify(AICallEvent.createEvent("aICallout", JSON.stringify(callParameter), "外呼操作")));
            //重置参数值
            waitForCall = false;
            hadReceiveCommitSuccess = false;
            sessionId = callVo.sessionId;
            formType = callVo.formType;
            isCallEnd = false;
            currentMsgType = "";
            desc = "";
            isRedial = false;
            isDoNextCall = false;
            selCustomerFollowVal = null;
            targetAnswer = false;
            isSaveFeedBack = false;
            isCloseWin = false;
            isChangePc = false;//重置参数
            interruptCheckStatus = false;
            reConnectToCallCount = 3;
        } else {
            layer.msg("已无可外呼的号码了");
        }
    } catch (e) {
        layer.msg("通知鸽子送信操作异常了！" + e.message);
    }
}

//为了保证外呼成功===外呼都需检测ws窗体是否存在===>正常情况下都会存在
function callNew() {
    if (callVo != null) {
        //检测外呼窗体是否存在
        console.log("当前通话id:"+sessionId+"窗体发送消息前，首先得看看“信鸽”还存不存在！");
        waitForCall = true;//设置等待外呼操作为true===>通过该标识来控制是否 “在进行检测时”如果判断连接正常时进行外呼操作


       // 测试界面试用
       /* for(var i=0;i<20;i++){
            getSaleAnswer("推荐话术："+"a"+i,"a"+i);
            getCustomerAnswer("推荐话术："+"b"+i,"b"+i);
            getRecommendAnswer("推荐话术："+"c"+i)
            $("#b"+i + " .tip_recordboxme .keyword_span").html("发起通话例行检查发起通话例行检查");
        }
        return;*/


        //通过广播形式检测外呼窗体是否存在 ==》 如果存在,则持有连接的页面 会通过广播形式 ==》 existsWs 通知给页面
        localStorage.setItem("AICallEvent", JSON.stringify(AICallEvent.createEvent("checkIsExists", sessionId, "通话id:"+sessionId+"发起通话例行检查")));//=====如果检测成功情况下，会接收到到existsWs值

        //定时检测外呼是否 ==== 设置个定时任务进行检测==如果逾时未收到回执==》可视作异常情况
        if (timeOutToCallTarget == null) {
            timeOutToCallTarget = setTimeout(function () {//如果接收到，则waitForCall = false不触发，否则触发发起重连ws再外呼操作
                if (waitForCall == true) { //
                    console.log("过了3s，发现没有接收到信鸽存在信息，或者目前存在的信鸽状态异常，发不了信息了，赶紧找个新的信鸽！");
                    // localStorage.setItem("reConnWs",new Date());
                    localStorage.setItem("AICallEvent", JSON.stringify(AICallEvent.createEvent("reConnWs", getNowDateyyyyMMddHHmmss() +"_"+ callVo.sessionId, "发起让各个页面抢夺重连Ws的操作")));
                    console.log("需要重新找个新的信鸽进行送信操作才行，设定6s等待查看他们是否找到信鸽");
                    reCallTask = setTimeout("checkWSStatus()", 6000);//8s后再检查是否有新的鸽子了
                }
            }, 3000);
        }
    } else {
        layer.msg("已无可外呼的号码了");
    }
}


//拼接webSocket的Url参数
var UrlParameter = {
    buildParam: function (url, userId, machineId, pageFrom) {
        var urlParameter = {};
        urlParameter.url = url;
        urlParameter.userId = userId;
        urlParameter.machineId = machineId;
        urlParameter.pageFrom = pageFrom;
        urlParameter.windowFrameId = frameId;
        return urlParameter;
    }
};


//拼接通话传递的参数
var CallParameter = {
    buildParam: function (mainCallPhone, targetCallPhone, whereFrom, pageFrom, machineFrom, mainCallType, commitTo, createUserId, customerName, callToken, cityId, isRedial, sessionId, callTaskId, connWsId, packageId,dataId) {
        var callParameter = {};
        callParameter.mainCallPhone = mainCallPhone;
        callParameter.targetCallPhone = targetCallPhone;
        callParameter.whereFrom = whereFrom;
        callParameter.pageFrom = pageFrom;
        callParameter.machineFrom = machineFrom;
        callParameter.mainCallType = mainCallType;
        callParameter.commitTo = commitTo;
        callParameter.createUserId = createUserId;
        callParameter.customerName = customerName;
        callParameter.callToken = callToken;
        callParameter.cityId = cityId;
        callParameter.project = "";
        callParameter.sessionId = sessionId;
        callParameter.connectWindowFrameId = frameId;
        callParameter.autoRedial = isRedial;
        callParameter.callTaskId = callTaskId;
        callParameter.updateTime = new Date().getTime();
        callParameter.connWsId = connWsId;
        callParameter.packageId = packageId;
        callParameter.packageName = callVo.packageName;
        callParameter.objectId = callVo.objectId;
        callParameter.aiCall = aiCall;
        callParameter.freeswitchCall=freeswitchCall;
        callParameter.actionCodeBreak = actionCodeBreak==true?1:0;
        callParameter.voiceCode = voiceCode;
        callParameter.dataId = dataId;
        callParameter.voiceText = voiceText;
        return callParameter;
    }
};


///监听 localStorage，如值发生变化才会过来 监听得到
window.addEventListener("storage", function (event) {
    if (event.key == "WebSocketEvent") {
        console.log("=====EventListenerToDo=====" + event.newValue);
        callbackPC(JSON.parse(event.newValue));
    }
    if (event.key == "ErrorEvent") {
        showErrorMsg(JSON.parse(event.newValue));
    }
    if (event.key == "TipsMsgEvent") {
        doSomethingFotyTip(event.newValue);
    }
});

//用于接收webscoket的信息
function callbackPC(data) {
    switch (data.type) {
        case "open":
            if(receiveCallMessage = false){//当从未接收过外呼信息时 ，返回对应的连接成功状态
                console.log("已为您接入云呼系统 onOpen-> " + new Date());
                showStatusForPage("已为您接入云呼系统");
            }
            break;
        case "message":
            receiveCallMessage = true;//接收到 外呼时的 信息
            var messageData = JSON.parse(data.value);
            //当判断传递过来的数据 dataID以及是pageFrom_PC一致情况下，才做接收处理
            if (messageData["sessionId"] == sessionId) {
                if (lastMsg != "" && (messageData["sessionId"] == lastMsg.sessionId && messageData["msgType"] == lastMsg.msgType)) {
                    if (messageData["msgType"] == "WORDS") {
                        console.log(messageData["id"] + "=======>" + lastMsg.id);
                        if (messageData["id"] == lastMsg.id) {
                            console.log("==========重复数据不做处理==========");
                            return;
                        }
                    }else if(messageData["msgType"] == "SPEAKING"){
                        if (messageData["wordId"] == lastMsg.wordId) {
                            console.log("==========重复数据不做处理==========");
                            return;
                        }
                    } else {
                        console.log("==========重复数据不做处理==========");
                        return;
                    }
                }
                lastMsg = messageData;
                console.log("onMessage-> " + data.value + new Date());
                var str = data.value;
                callPhoneManager(str, formType);
            }
            break;
        case "error":
            console.log("onError-> " + new Date());
            showStatusForPage("通话异常");
            break;
        case "close":
            console.log("onClose-> " + new Date());
            showStatusForPage("通话结束");
            break;
        default:
            break;
    }
}


//用于接收通话返回的情况
function callPhoneManager(jsonStr, formType) {
    var dataObj = JSON.parse(jsonStr);
    var msgType = dataObj["msgType"];
    currentMsgType = dataObj["msgType"];

    desc = dataObj["desc"];
    console.log("=======" + msgType + "=========");
    switch (msgType) {
        case 'COMMIT_SUCCESS':
            showStatusForPage("请耐心等候!");
            $("#showNum").css("display", "");
            console.log(dataObj["showNum"]);
            $("#showNumTxt").html(dataObj["showNum"]);
            hadReceiveCommitSuccess = true;
            //todo 发起外呼有返回的情况下，刷新文本数据
            $(".jspPane").children().each(function (idx, elem) {
                var elem = $(elem);
                if (elem != undefined) {
                    elem.remove();
                }
            });
            //重置计时器
            var t = "00:00:00";
            $("#connectTime").html(t);
            //重置反馈
            selCustomerFollowVal = $("input[name='customerFollowCategory']:checked").val();
            if(selCustomerFollowVal!=null && selCustomerFollowVal!=undefined && selCustomerFollowVal!=-1 && selCustomerFollowVal!=""){
                $("input[name=customerFollowCategory][value='"+selCustomerFollowVal+"']").attr("checked", false);//自动匹配“电话挂机”
            }
            if(aiCall == true && voiceText!=""){//如果是单呼情况下===外呼头像显示机器人 ，且提交成功时，显示开场白
                getRobotAnswer(voiceText,sessionId);
                // getRecommendAnswer("推荐话术："+voiceText);
            }
            break;
        case 'MAIN_RINGING'://主叫响铃
            showStatusForPage("正为您呼叫客户中，请稍候!");
            break;
        case 'MAIN_ANSWERED'://主叫应答
            showStatusForPage("已为您接通客户@^_^@");
            break;
        case 'TARGET_RINGING'://被叫响铃
            if(commitTo == 8){
                showStatusForPage("留意您的号码，是否响铃了");
            }else{
                showStatusForPage("留意您的号码，是否响铃了");
            }
            break;
        case 'TARGET_ANSWERED'://被叫应答
            targetAnswer = true;
            showStatusForPage("通话中");
            if (isStartTimeTask == false) {
                startTime();//开始通话计时--js
            }
            break;
        case 'MAIN_DISCONNECTED'://主叫结束通话
            stopTime();
            showStatusForPage("客户结束了通话!");
            isCallEnd = true;
            if (targetAnswer == true) {
                var connectionTime = $("#connectTime").html();//zk.Widget.$('$connectionTime').getValue();
                var conn = connectionTime.split(":");
                var hour = conn[0];
                var min = conn[1];
                var second = conn[2];
                if (hour <= 0 && min <= 0 && second <= 0) {//没有通话时长情况下 ===》 主叫结束
                    $("input[name=customerFollowCategory][value='oh']").attr("checked", true);//自动匹配“电话挂机”
                    saveFeedBack("oh", false);//默认是电话挂机
                }
            }
            break;
        case 'TARGET_DISCONNECTED'://主叫结束通话
            showStatusForPage("通话结束！");
            isCallEnd = true;
            break;
        case 'MAIN_FAILED'://主叫失败
            showStatusForPage("无法接通客户...");
            isCallEnd = true;
            $("input[name=customerFollowCategory][value='nor']").attr("checked", true);//自动匹配“无人接通”
            selCustomerFollowVal = $("input[name='customerFollowCategory']:checked").val();
            saveFeedBack(selCustomerFollowVal, false);//默认是电话挂机
            break;
        case 'TARGET_FAILED'://被叫失败
            showStatusForPage("无法呼叫您的号码...");
            isCallEnd = true;
            break;
        case 'COMMIT_FAILED'://提交失败
            isCallEnd = true;
            isCallException = true;
            showStatusForPage("外呼失败");
            layer.msg(desc);
            setAutoCall(false, null);
            break;
        case 'EXCEPTION'://异常
            isCallEnd = true;
            layer.msg(desc);
            showStatusForPage(desc);
            isCallException = true;
            setAutoCall(false, null);
            break;
        case "APP_START":
            showStatusForPage("APP开始外呼操作");
            break;
        case "APP_STOP":
            showStatusForPage("APP停止了外呼操作");
            isCallEnd = true;
            break;
        case "APP_ERROR":
            isCallException = true;
            showStatusForPage("APP呼叫异常");
            break;
        case "VOICE_MSG":
            showStatusForPage("识别的信息");
            break;
        case "APP_DISCONNECT":
            showStatusForPage("APP进行挂断操作");
            isCallEnd = true;
            break;
        case "WORDS":
            var type = dataObj["role"];
            var words = dataObj["words"];
            var wordsId = dataObj["wordId"];
            if(words!=null && words!=undefined && words.trim()!=""){
                if ("customer" == type) {
                    getCustomerAnswer(words, wordsId);
                } else if ("broker" == type) {
                    getSaleAnswer(words, wordsId);
                }
            }
            break;
        case "SPEAKING":
            var speaking = dataObj["speaking"];
            var matchType = dataObj["matchType"];
            if (matchType != "") {
                var matchValue = dataObj["matchValue"];
                var matchKeyWords = dataObj["matchKeyWords"];
                var wordId = dataObj["wordId"];
                var matchValue = dataObj["matchValue"];
                var affect_type = dataObj["affect_type"];
                console.log("affect_type:"+affect_type+","+matchType + ":" + matchValue + "===>" + matchKeyWords);
                if(matchType=='知识库' && affect_type == 'COMMON'){
                    matchType = '公共知识库';
                }else{
                    matchType = '项目知识库';
                }
                var val = "匹配到" + matchType + ":" + "【" + matchValue + "】";
                if(matchType == "无"){
                    val = "未匹配到问题/回答分支，待学习";
                }
                if(matchKeyWords!=""){
                    val += ",关键词：" + matchKeyWords;
                }
                // var val = "匹配到" + matchType + ":" + "【" + matchValue + "】,关键词：" + matchKeyWords;
                console.log(val);
                $("#" + wordId + " .tip_recordboxme .keyword_span").html(val);
                jspapi.reinitialise();
                jspapi.scrollToBottom();
            }

            if(speaking!=null && speaking!=undefined && speaking.trim()!=""){
                if(aiCall == true){//如果是单呼情况下===外呼头像显示机器人 ，且提交成功时，显示开场白
                    getRobotAnswer(speaking,sessionId +"_"+robotAnswerId);
                    if(speaking.action == 'hangup'){
                        $("#" + sessionId +"_"+robotAnswerId + " .tip_recordboxme .keyword_span").html("触发挂机操作，通话结束。");
                    }
                }else{
                    getRecommendAnswer("推荐话术："+speaking);
                }
            }
            break;
        case "WEBSOCKET_TOO_MANY_CONNECT_MSG":
            console.log("连接的窗体过多");
            break;
        case "WEBSOCKET_NOT_RECONNECT_MSG"://断开后---不需要重新连接websocket
            console.log("断开后---不需要重新连接websocket");
            break;
        case "WEBSOCKET_CHANGE_PC_MSG":
            console.log("需要切换电脑进行外呼操作？");
            break;
        default:
            break;
    }

    if (isCallEnd == true) {//判断是外呼结束时，
        stopTime();//暂停计时器
        if (isAutoCall == true) {
            doNextCall();
        }
    }
}




function startTime() {
    if (second > 0 && (second % 60) == 0) {
        min += 1;
        second = 0;
    }
    if (min > 0 && (min % 60) == 0) {
        hour += 1;
        min = 0;
    }
    var str1 = hour < 10 ? "0" + hour : hour;
    var str2 = min < 10 ? "0" + min : min;
    var str3 = second < 10 ? "0" + second : second;
    var t = str1 + ":" + str2 + ":" + str3;
    $("#connectTime").html(t);
    second += 1;
    isStartTimeTask = true;// 标识执行计时任务中
    startTimeTask = setTimeout(function () {
        startTime();
    }, 1000);
}


function stopTime() {
    console.log("=====结束通话计时=====");
    clearTimeout(startTimeTask);//清除计时任务
    isStartTimeTask = false;
    startTimeTask = null;
    min = 0;
    hour = 0;
    second = 0;

}

function getCustomerAnswer(content, id) {
    console.log("=======getCustomerAnswer====");
    // var imgUrl = baseUrl + "/images/15.jpg";
    var imgUrl = baseUrl + "/images/callDetail/customer.png";
    var objStr = '<div id="' + id + '" class="talk_recordboxme">\n' +
        '                        <div class="user"><img  src="' + imgUrl + '" />客户</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                       <div  class="tip_recordboxme">\n' +
        '                             <span class="keyword_span" style="padding: 5px">\n' +
        '                             </span>\n' +
        '                        </div>' +
        '                    </div>' +
        '<div class="clear"></div>';

    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}

function getSaleAnswer(content, id) {
    console.log("=======getSaleAnswer====");
    // var imgUrl = baseUrl + "/images/11.jpg";
    var imgUrl = baseUrl + "/images/callDetail/sale.png"; // /images/11.jpg
    var objStr = '<div  id="' + id + '" class="talk_recordbox">\n' +
        '                        <div class="user"><img src="' + imgUrl + '" />经纪</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                    </div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}

function getRecommendAnswer(content) {
    var objStr = '<div class="tip_msg_recordboxme" >' +
        '<div class="talk_msg_recordtext" >' +
        '<span>' + content + '</span>' +
        '</div></div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}


function getRobotAnswer(content, id) {
    robotAnswerId ++;
    console.log("=======getRobotAnswer====");
    var imgUrl = baseUrl + "/images/callDetail/robot.png"; // /images/11.jpg
    var objStr = '<div  id="' + id + '" class="talk_recordbox">\n' +
        '                        <div class="user"><img class="header-icon" src="' + imgUrl + '" />萝卜仔</div>\n' +
        '                        <div class="talk_recordtextbg">&nbsp;</div>\n' +
        '                        <div class="talk_recordtext">\n' +
        '                            <h3>' + content + '</h3>\n' +
        '                        </div>\n' +
        '                       <div  class="tip_recordboxme">\n' +
        '                             <span class="keyword_span" style="padding: 5px">\n' +
        '                             </span>\n' +
        '                        </div>' +
        '                    </div>' +
        '<div class="clear"></div>';
    $(".jspPane").append(objStr);
    //重新加载刷新滚动条
    jspapi.reinitialise();
    jspapi.scrollToBottom();
}

//挂断操作 cancelWay-->挂断方式
function interruptCall(cancelWay) {
    if (hadReceiveCommitSuccess == false) {
        layer.msg("当前通话尚未创建成功，无法进行挂断操作!");
        isCallEnd = false;
        return;
    }
    if (isCallEnd == false) {
        console.log("===通话sessionId===" + sessionId);
        var params = "";
        console.log("====执行挂断操作===(方式:" + cancelWay + ") :" + sessionId + new Date());
        switch (cancelWay) {
            case "auto":
                params = "sessionId=" + sessionId + "&autoInterrupt=true";
                break;
            case "manual":
                params = "sessionId=" + sessionId + "&autoInterrupt=false";
                break;
            case "closeWin":
                params = "sessionId=" + sessionId + "&autoInterrupt=false";
                break;
            default:
                break;
        }
        ajaxInterrupt(cancelWay, params);
    }
}

function ajaxInterrupt(cancelWay, params) {
    console.log("===================ajaxInterrupt========================="+cancelWay+","+params);
    var isAsync = true;// 是否异步操作
    if (cancelWay == "closeWin") {
        isAsync = false;
    }
    //假如是freeswitch进行外呼,进入freeswitch
    if(freeswitchCall){
        var trueInterruptCallUrl=freeswitchCallService + "/freeswitch/interruptCall";
    }else{

        var trueInterruptCallUrl=interruptCallUrl;
    }
    console.log(trueInterruptCallUrl + "?" + params);
    $.ajax({
        type: "get",
        async: isAsync,
        url: trueInterruptCallUrl + "?" + params,
        dataType: "jsonp",//数据类型为jsonp
        jsonp: "jsonpCallBack",//服务端用于接收callback调用的function名的参数
        success: function (data) {
            if (data.code > 0) {//正常的结束
                console.log("挂断成功");
                isCancelCall = true;//是否执行挂断操作
                stopTime();//停止计时--js
                //将挂断信息传递到云呼反馈值中
                /* desc = data.msg;
                 $("#desc").val(desc);*/
                showStatusForPage("挂断成功");
                isCallEnd = true;//挂断成功同时---标志该通话状态为结束
                if (cancelWay == "manual") {//----手动挂断情况下
                    setAutoCall(false, null);
                    layer.msg("已经为您成功挂断操作");
                } else {
                    //默认将客户反馈填写为无人接听
                    if (isAutoCall == true) {
                        doNextCall(); //执行下一通外呼操作
                    }
                }
            } else {
                layer.msg("挂断操作失败,请稍候再重试");
                //挂断按钮可用
                // document.getElementById("buttonCallCannel").disabled = false;
            }
        },
        error: function () {
            console.log("发送http挂断操作失败");
        }
    });
}

//保存反馈操作
function saveFeedBack(selCustomerFollowVal, closeWin) {
    if (isSaveFeedBack == true) {
        console.log("已保存了反馈，不再操作");
        return;
    }
    var isAsync = true;// 是否异步操作
    if (isCloseWin == true) {
        isAsync = false;
    }
    if(sessionId==undefined || sessionId=="" || sessionId==null){
        console.log("通话未生成");
        return;
    }
    $.ajax({
        type: "POST",
        async: isAsync,
        url: baseUrl + '/linkageCall/saveFeedBack?sessionId=' + sessionId + '&feedBack=' + selCustomerFollowVal,
        dataType: 'json',
        success: function (data) {
            if (data != null) {
                if (data.code > 0) {
                    layer.msg("保存反馈操作成功");
                } else {
                    layer.msg("保存反馈操作失败");
                }
            } else {
                layer.msg("保存反馈操作失败");
            }
        },
        error: function (res) {
            console.log(res);
            layer.msg("保存反馈操作失败");
        }
    });
    if (closeWin == true) {//如果关闭窗体 进来的保存反馈 ===》如果是异常情况下，则---》忽略直接关闭窗体
        var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        parent.layer.close(currentIndex); //再执行关闭，强制关闭弹窗
    }
    selCustomerFollowVal = null;
    isSaveFeedBack = false;
}

//获取下一个
function doNextCall() {
    if (isDoNextCall == false && isCallEnd == true && isCloseWin == false && isAutoCall == true) {
        if (selCustomerFollowVal == null) {
            layer.msg("请选择反馈，再执行call下一个客户!");
            return;
        }
        isDoNextCall = true;
        var load = layer.msg('正为您进行呼叫下一个客户，请稍候', {icon: 16, time: false, shade: 0.8});
        showStatusForPage("正为您进行呼叫下一个客户，请稍候");

        if(setMainCallPhone!="" && (regTxt.test(setMainCallPhone) || regTelPhoneTxt.test(setMainCallPhone))){
            setMainCallPhone = setMainCallPhone;
        }else{
            setMainCallPhone = "";
        }
        var callNextTask = setTimeout(function () {
            $.ajax({
                type: "POST",
                async: false,
                url: baseUrl + '/linkageCall/getNextPhone?taskId=' + taskId + '&packageName='+callVo.packageName +'&targetCallPhone=' + setTargetCallPhone + '&mainCallPhone=' + setMainCallPhone +'&taskNum='+1,
                dataType: 'json',
                success: function (data) {
                    layer.close(load);
                    if (data != null) {
                        console.log(JSON.stringify(data));
                        callVo = data;
                        sessionId = callVo.sessionId;
                        if (callVo != null) {
                            $("#customerName").text(callVo.customerName);
                            $("#targetCallPhone").text(callVo.targetCallPhone);
                            $("#mainCallPhone").text(callVo.mainCallPhone);
                            $("#callTime").text(getNowDateyyyyMMddHHmmss());
                            callNew();
                        }
                    } else {
                        layer.msg("该资料包已被call完");
                        return;
                    }
                },
                error: function (res) {
                    console.log(res);
                    layer.close(load);
                    layer.msg("操作失败");
                    return;
                }
            });
            if ($("input[name='customerFollowCategory']:checked") != undefined) {
                $("input[name='customerFollowCategory']:checked").checked = false;//取消选中
                selCustomerFollowVal = null;
            }
            saveFeedBack(selCustomerFollowVal, false);//执行下一通call客时，进行保存反馈操作===》避免多次操作
            clearTimeout(callNextTask);
        }, 5000);
    }
}

//暂停自动call客
function setAutoCall(autoCall, load) {
    isAutoCall = autoCall;
    if (autoCall == false) {
        console.log("暂停自动call客");
        $("#callNext").disabled = false;//设置下一条为可用
        if (load == null) {
            layer.msg("外呼失败，已为您暂停自动call客");
            $("#stopAutoCall").html("暂停自动call");
        }
        stopTime();//暂停倒计时
        //如果当前是通话情况下=== 暂停自动call客，进行挂断操作
        if (isCallEnd == false) {
            interruptCall("manual");
        }
    } else {
        $("#callNext").disabled = true;//设置下一条为不可用
        if (load == null) {
            layer.msg("执行下一条call客操作，已为你恢复自动call客");
            $("#stopAutoCall").html("恢复自动call");
        }
    }
    if (load != null) {
        layer.close(load);
    }
}

$("#stopAutoCall").click(function () {
    var txt = $("#stopAutoCall").html();
    if (txt == "暂停自动call") {
        var load = layer.msg('正为您暂停自动call客，请稍候', {icon: 16, time: false, shade: 0.8});
        $("#stopAutoCall").html("恢复自动call");
        setAutoCall(false, load);
    } else {
        var load = layer.msg('正为您恢复自动call客，请稍候', {icon: 16, time: false, shade: 0.8});
        $("#stopAutoCall").html("暂停自动call");
        setAutoCall(true, load);
    }
});


$("#callNext").click(function () {
    if ((isCallEnd == false || isDoNextCall == true)&& isCallException == false) {
        layer.msg("目前正有通话正在进行中，无法进行下一通call客...")
    } else {
        if (isAutoCall == false) {
            setAutoCall(true, null);
        }
        doNextCall();
    }
});

//手动触发中断操作
$("#interruptCall").click(function () {
    interruptCall("manual");
});

//重拨
$("#reDial").click(function () {
    //判断是通话结束 或者 是通话异常[视作为结束]
    if(isCallEnd== true || isCallException==true){
        if (callVo == null) {
            layer.msg("重拨操作失败，暂无可外呼的号码");
        } else {
            var load = layer.msg('正为您进行重拨操作，请稍候', {icon: 16, time: false, shade: 0.8});
            $.ajax({
                type: "POST",
                async: false,
                /*dataType:"json",*/
                url: baseUrl + '/linkageCall/getSessionId',
                success: function (data) {
                    layer.close(load);
                    callVo.sessionId = data;
                    sessionId = callVo.sessionId;
                    //重置参数
                    isChangePc = false;
                    interruptCheckStatus = false;
                    callNew();
                },
                error: function (res) {
                    console.log(e.message);
                    layer.close(load);
                    layer.msg("操作失败");
                }
            });
        }
    }else{
        layer.msg("通话进行中无法进行此操作");
    }
});

// 跟进反馈被选中触发
$(".customerFollowCategoryRadio").click(function () {
    selCustomerFollowVal = $("input[name='customerFollowCategory']:checked").val();
    if (selCustomerFollowVal != "" && selCustomerFollowVal != undefined && isAutoCall == true) {//执行下一call客操作
        doNextCall();
    }
});


//跟进tip 的type值，做出相应的回应[操作]
function doSomethingFotyTip(tipMsg) {
    try {
        var tipObj = JSON.parse(tipMsg);
            console.log("sessionId 相同？ ==》 " + (callVo.sessionId == tipObj.sessionId));
            if (callVo != null && callVo.sessionId == tipObj.sessionId) {
                switch (tipObj.type) {
                    case "existsWs": //连接存在 ===》 发送外呼操作？？
                        /**
                         * 检测存在时，这个状态是由广播返回而来的，需要对广播信息进行过滤，避免处理多余的状态
                         *
                         * 通过sessionId 来判断 是否当前页面发送的外呼
                         * */
                        console.log("信鸽在这里啊！");
                        var desc = tipObj.desc;
                        console.log("判断这个信鸽是否还存活，看看它是不是还有心跳，是否正常健康");
                        var heartbeatEvent = localStorage.getItem("heartbeatEvent");
                        if (heartbeatEvent != null) {
                            var heartbeatObj = JSON.parse(heartbeatEvent);
                            var ms = new Date().getTime() - heartbeatObj.time;   //时间差的毫秒数
                            console.log(ms);
                            if (ms <= 7000) {//5s内响应情况下 ==》 存在且可以外呼操作
                                waitForCall = false;
                                connWsId = heartbeatObj.id;//将存在的wsid打包给外呼，指定是用哪个鸽子进行送信
                                console.log("信鸽目前很健康，可以进行送信操作了");
                                call();
                            } else {//一般是不存在===== 由于设置了检测后，触发个定时检测操作任务，所以超时未反馈 暂不做处理
                                if(isChangePc==true){
                                    isRedial  = true;//重拨操作
                                    call();
                                }else{
                                    console.log("连接异常====》设置等待外呼操作为true");
                                    waitForCall = true;
                                    return;
                                }
                            }
                        } else {
                            console.log("无法接收到信鸽它心跳情况，无法判断是否健康，将会再重新获取信鸽");
                        }
                        break;
                    case "tooManyConnectMsg":
                        console.log("太多窗体进行外呼操作了");
                        isCallException = true;
                        showStatusForPage(tipObj.desc);
                        interruptCheckStatus = true;
                        break;
                    case "error":
                    case "callError":
                        showStatusForPage(tipObj.desc);
                        layer.msg("连接异常，请刷新后再进行外呼的操作吧!!!");
                        receiveCloseCall("连接异常，请刷新后再进行外呼的操作吧!!!");
                        break;
                    case "callSuccess":
                        showStatusForPage("已经为您发起了外呼操作");
                        break;
                    case "changePC":
                        interruptCheckStatus = true;
                        layer.confirm(tipObj.desc+"是否要进行切换PC操作", {
                            btn: ['确定', '取消'],
                            closeBtn:0
                        }, function (index, layero) {
                            isChangePc = true;
                            localStorage.setItem("AICallEvent", JSON.stringify(AICallEvent.createEvent("changePc", callVo.createUserId, "切换PC进行外呼操作")));
                            return;
                        }, function (index) {
                            isCallException = true;
                            isCallEnd = true;
                            token = "";
                            isChangePc = false;
                            localStorage.setItem("AICallEvent", JSON.stringify(AICallEvent.createEvent("notChangePc", callVo.createUserId, "不切换PC进行外呼操作")));
                            return;
                        });
                        break;
                    case "websocketChangePCMsg":
                        layer.msg("切换PC操作成功，正为您进行重拨操作");
                        isCallException = true;
                        isCallEnd = true;
                        interruptCheckStatus = true;
                        call();//再次执行callNew操作
                        break;
                    default:
                        break;
                }
            }
    } catch (e) {
        console.log("按ws提示类别返回相应的处理，操作异常：" + e.message);
    }
}

//定时触发===自动去查看有没有找到正常信鸽且信鸽是否正常
function checkWSStatus() {
    console.log("6s后查看信鸽状态是否正常");
    clearTimeout(timeOutToCallTarget);
    clearTimeout(reCallTask);
    timeOutToCallTarget = null;
    reCallTask = null;
    try {
        console.log("interruptCheckStatus:"+interruptCheckStatus);
        if(interruptCheckStatus==false){
            var heartbeatEvent = localStorage.getItem("heartbeatEvent");
            console.log(heartbeatEvent);
            if (heartbeatEvent != null) {
                var heartbeatObj = JSON.parse(heartbeatEvent);
                var ms = new Date().getTime() - heartbeatObj.time;   //时间差的毫秒数
                if (ms < 6000) {//如果接受时间判断已超时==》异常的心跳情况 ===》抢夺政权
                    console.log("检测目前信鸽" + heartbeatObj.id + "是正常的健康的，马上执行送信操作");
                    connWsId = heartbeatObj.id;
                    call();
                }else{
                    console.log("reConnectToCallCount==============>"+reConnectToCallCount);
                    if(reConnectToCallCount>0){
                        console.log("检测连接状态，重试次数 ===>"+reConnectToCallCount);
                        showStatusForPage("检测连接状态，请稍候!");
                        reConnectToCallCount --;
                        if(reCallTask!=null)
                            reCallTask = setTimeout("checkWSStatus()", 6000);//6s后再检查是否有新的鸽子了
                    }else{
                        receiveCloseCall("检测连接状态失败，请稍候再试吧！");
                    }
                }
            } else {
                console.log("reConnectToCallCount==============>"+reConnectToCallCount);
                if(reConnectToCallCount>0){
                    console.log("检测连接状态，重试次数"+reConnectToCallCount);
                    showStatusForPage("检测连接状态，请稍候!");
                    reConnectToCallCount --;
                    reCallTask = setTimeout("checkWSStatus()", 6000);//8s后再检查是否有新的鸽子了
                }else{
                    receiveCloseCall("检测连接状态失败，请稍候再试吧！")
                }
            }
        }
    } catch (e) {
        layer.msg("连接外呼有异常，请刷新后再进行外呼的操作吧！");
        console.log("自动检测信鸽状态操作异常:" + e.message);
    }
}


//跟进ws 返回的异常信息进行处理
function showErrorMsg(errorMsg) {
    var errorObj = JSON.parse("errorMsg");
    if (errorObj != null) {
        layer.msg(errorObj.desc);
    }
}


//关闭窗体
$("#closeWin").click(function () {
    try {
        var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        if(sessionId==null && sessionId=="" && sessionId==undefined){
            isCallException = true;
        }
        if (isCallException == true) {
            parent.layer.close(currentIndex); //再执行关闭，强制关闭弹窗
            return;
        }
        isCloseWin = false;
        if (isCallEnd == false) {
            layer.confirm('通话尚未结束，您确定要结束此通话？', {
                btn: ['确定', '取消'],
            }, function (index, layero) {
                isCloseWin = true;
                if (hadReceiveCommitSuccess == true) {//接收到 提交成功情况下 ===》 进行挂断操作
                    interruptCall("closeWin");
                }
                if (isSaveFeedBack == false || selCustomerFollowVal == null) {
                    saveFeedBack("oh", isCloseWin);//默认是电话挂机
                }
                parent.layer.close(currentIndex); //再执行关闭，强制关闭弹窗
            }, function (index) {
                isDoNextCall = false;
                return;
            });
        } else {
            if (isSaveFeedBack == false && selCustomerFollowVal != null) {
                saveFeedBack(selCustomerFollowVal, true);
            } else {
                /* //捕获页
                 tipWinIndex = layer.open({
                     type: 1,
                     shade: false,
                     title: false, //不显示标题
                     content: $('.layer_notice'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                     cancel: function(){
                         layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', {time: 5000, icon:6});
                     }
                 });*/

                layer.confirm('您还没有给通话选择对应的反馈，您确定不选择反馈直接关闭？', {
                    btn: ['确定', '取消'],
                    closeBtn:0
                }, function (index, layero) {
                    isCloseWin = true;
                    saveFeedBack("oh", isCloseWin);//默认是电话挂机
                }, function (index) {
                    isDoNextCall = false;
                    return;
                });
            }
        }
    } catch (e) {
        console.log("关闭操作异常:" + e.message);
        parent.layer.close(currentIndex); //再执行关闭，强制关闭弹窗
    }
});

/*$("#btnOk").click(function () {
    try {
        if (tipWinIndex != null) {
            parent.layer.close(tipWinIndex); //再执行关闭，强制关闭弹窗
        }
    } catch (e) {
        console.log("关闭提示弹出层异常");
        parent.layer.close(tipWinIndex); //再执行关闭，强制关闭弹窗
    }
});*/



//接收异常关闭外呼操作
function receiveCloseCall(desc) {
    console.log("接收外呼结束状态 ==========》接收异常状态："+desc);
    waitForCall = false;
    isCallEnd = true;
    isCallException = true;
    reConnectToCallCount = 0;
    interruptCheckStatus = true;
    showStatusForPage(desc);
    return;
}

function showStatusForPage(desc) {
    if ($("#txResult").length > 0){
        $("#txResult").html(desc);
    }
    if ($("#txResultMsg").length > 0){
        $("#txResultMsg").html(desc);
    }
}

function  getNowDateyyyyMMddHHmmss() {
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth()+1;
    var date = d.getDate();
    var day = d.getDay();
    var hours = d.getHours();
    var minutes = d.getMinutes();
    var seconds = d.getSeconds();
    var ms = d.getMilliseconds();
    var curDateTime= year;
    if(month>9)
        curDateTime = curDateTime +"-"+month;
    else
        curDateTime = curDateTime +"-0"+month;
    if(date>9)
        curDateTime = curDateTime +"-"+date;
    else
        curDateTime = curDateTime +"-0"+date;
    if(hours>9)
        curDateTime = curDateTime +""+hours;
    else
        curDateTime = curDateTime +"0"+hours;
    if(minutes>9)
        curDateTime = curDateTime +":"+minutes;
    else
        curDateTime = curDateTime +":0"+minutes;
    if(seconds>9)
        curDateTime = curDateTime +":"+seconds;
    else
        curDateTime = curDateTime +":0"+seconds;
    return curDateTime;
}

window.onunload = function () {
    var params = "sessionId=" + sessionId + "&autoInterrupt=false";
    ajaxInterrupt("closeWin", params);
};

/**
 * 返回确认提示框
 */
function showConfrimMsg(desc){
    parent.layer.confirm(desc, {
        btn: ['确定'],
        closeBtn:0
    }, function (index, layero) {
        var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        parent.layer.close(currentIndex); //再执行关闭，强制关闭弹窗
        parent.layer.close(index);
        return;
    });
}

/*
*  后台程序执行时返回异常信息  errorMsg 如果不为空 则直接提示 ==》无法使用
*       否则
*           判断是否有外呼的号码对象【callVo】
*                如果有则进行检测外呼操作  【如：是智能外呼操作[aiCall = true],需带有开场白流程信息才能进行】
*                如果没有则返回提示
* */
if(errorMsg!=null && errorMsg!=undefined && errorMsg!=""){
    showConfrimMsg(desc);
}else{
    if(callVo == null){
        showConfrimMsg("资料包已Call完……");
    }else{
        if((aiCall==true && (voiceText!=null && voiceText!="")) || aiCall==false){
            //加多一层校验 防止后台多次判断 号码的正确性
            if(aiCall==false && (setTargetCallPhone == "" || setTargetCallPhone==null ||  setTargetCallPhone.toUpperCase()=="NULL"
                    || !regTxt.test(setTargetCallPhone) && !regTelPhoneTxt.test(setTargetCallPhone))){
                layer.msg("请先设置call客号码，再进行外呼操作!");
            }else{
                checkCanCall();
            }
        }else{
            showConfrimMsg("请设置对应话术包的开场白话术吧");
        }
    }
}